/**
 * MainActivity - 脑波应用主界面
 * 
 * 该文件是应用的主入口，展示脑波频域泳道图组件
 * 集成了SwimLaneChart组件，提供实时脑波数据可视化
 * 新增蓝牙连接功能，支持NeuroSky设备直接连接
 * 
 * 功能：
 * - 显示脑波频域泳道图
 * - 提供实时数据可视化界面
 * - 展示数据统计信息
 * - 蓝牙设备连接和数据采集
 * 
 * 使用的组件：
 * - SwimLaneChart: 泳道图可视化组件
 * - SwimLaneChartViewModel: 数据管理ViewModel
 * - NeuroSkyBluetoothManager: 蓝牙连接管理器
 */

package com.example.brain_wave

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.Canvas
import androidx.compose.material3.*
import androidx.compose.material3.MenuAnchorType
import androidx.compose.runtime.*
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.windowInsetsPadding
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.graphics.Shadow
import androidx.compose.foundation.BorderStroke
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.brain_wave.ui.components.*
import com.example.brain_wave.ui.theme.Brain_waveTheme
import com.example.brain_wave.ui.theme.*
import androidx.compose.ui.platform.LocalContext
import com.example.brain_wave.bluetooth.NeuroSkyService
import com.example.brain_wave.bluetooth.session.SessionState
import com.example.brain_wave.config.AppConfig
import com.example.brain_wave.data.DataSourceManager
import com.example.brain_wave.data.DataSourceState
import com.example.brain_wave.data.AnalysisDataManager
import com.example.brain_wave.data.AnalysisDataManagerState
import com.example.brain_wave.api.model.TabletBrainWaveResponse

import com.example.brain_wave.bluetooth.api.SessionResponse
import com.example.brain_wave.ui.components.StoreRoomDataManager
import com.example.brain_wave.data.DataSourceType
import com.example.brain_wave.bluetooth.NeuroSkyBluetoothManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
    
    // 蓝牙管理器
    private lateinit var neuroSkyBluetoothManager: NeuroSkyBluetoothManager
    
    // 权限请求
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val allGranted = permissions.values.all { it }
        if (allGranted) {
            initializeBluetooth()
        } else {
            Toast.makeText(this, "需要蓝牙权限才能使用此功能", Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 测试日志输出 - 确认日志系统正常工作
        println("🚀 MainActivity onCreate 开始执行")
        println("🚀 MainActivity onCreate 开始执行 - println测试")
        println("🚀 MainActivity onCreate 开始执行 - android.util.Log测试")
        
        // 初始化蓝牙管理器
        neuroSkyBluetoothManager = NeuroSkyBluetoothManager(this)
        
        try {
            enableEdgeToEdge()
            setContent {
                Brain_waveTheme {
                    Surface(
                        modifier = Modifier.fillMaxSize(),
                        color = MaterialTheme.colorScheme.background
                    ) {
                        BrainWaveApp()
                    }
                }
            }
        } catch (e: Exception) {
            // 记录异常信息
            e.printStackTrace()
            // 显示错误信息给用户
            setContent {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "应用启动失败\n错误: ${e.message}",
                        color = Color.Red,
                        textAlign = TextAlign.Center
                    )
                }
            }
        }
        
        // 检查蓝牙权限
        checkBluetoothPermissions()
    }
    
    private fun checkBluetoothPermissions() {
        val permissions = mutableListOf<String>()
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            permissions.addAll(listOf(
                Manifest.permission.BLUETOOTH_SCAN,
                Manifest.permission.BLUETOOTH_CONNECT,
                Manifest.permission.ACCESS_FINE_LOCATION
            ))
        } else {
            permissions.addAll(listOf(
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION
            ))
        }
        
        val needPermissions = permissions.filter {
            ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }
        
        if (needPermissions.isNotEmpty()) {
            requestPermissionLauncher.launch(needPermissions.toTypedArray())
        } else {
            initializeBluetooth()
        }
    }
    
    private fun initializeBluetooth() {
        if (!neuroSkyBluetoothManager.isBluetoothAvailable()) {
            Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show()
            return
        }
        
        // 如果蓝牙未开启，请求开启 - 使用新的API获取BluetoothAdapter
        val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        val bluetoothAdapter = bluetoothManager.adapter
        if (bluetoothAdapter?.isEnabled != true) {
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                startActivity(enableBtIntent)
            }
        }
    }
    
    // 获取蓝牙管理器实例，供Compose组件使用
    fun getBluetoothManager(): NeuroSkyBluetoothManager = neuroSkyBluetoothManager
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TimeWindowDropdown(
    currentSelection: Int,
    onSelectionChange: (Int) -> Unit,
    modifier: Modifier = Modifier
) {
    var expanded by remember { mutableStateOf(false) }
    val options = SwimLaneChartConfig.TIME_WINDOW_OPTIONS
    
    ExposedDropdownMenuBox(
        expanded = expanded,
        onExpandedChange = { expanded = !expanded },
        modifier = modifier
    ) {
        OutlinedTextField(
            value = options.find { it.first == currentSelection }?.second ?: "${currentSelection}秒",
            onValueChange = { },
            readOnly = true,
            trailingIcon = {
                ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded)
            },
            colors = OutlinedTextFieldDefaults.colors(
                focusedTextColor = Color.White,
                unfocusedTextColor = Color.White,
                focusedBorderColor = Color(0xFF43A047),
                unfocusedBorderColor = Color.Gray
            ),
            modifier = Modifier
                .menuAnchor(MenuAnchorType.PrimaryNotEditable)
                .fillMaxWidth()
        )
        
        ExposedDropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false }
        ) {
            options.forEach { (seconds, label) ->
                DropdownMenuItem(
                    text = { Text(label, color = Color.White) },
                    onClick = {
                        onSelectionChange(seconds)
                        expanded = false
                    },
                    colors = MenuDefaults.itemColors(
                        textColor = Color.White
                    )
                )
            }
        }
    }
}

@Composable
fun BrainWaveApp() {
    val context = LocalContext.current
    val appConfig = remember { AppConfig.getInstance(context) }
    
    // 权限状态管理
    var hasBluetoothPermissions by remember { mutableStateOf(false) }
    
    // 使用权限管理组件包装主要内容
    BluetoothPermissionManager(
        onPermissionsResult = { granted ->
            hasBluetoothPermissions = granted
        }
    ) {
        // 权限授予后显示主要内容
        BrainWaveMainContent()
    }
}

@Composable
private fun BrainWaveMainContent() {
    val context = LocalContext.current
    val appConfig = remember { AppConfig.getInstance(context) }
    
    // 蓝牙管理器实例
    val bluetoothManager = remember { (context as MainActivity).getBluetoothManager() }
    
    // 门店房间选择状态
    var stores by remember { mutableStateOf<List<Store>>(emptyList()) }
    var rooms by remember { mutableStateOf<List<Room>>(emptyList()) }
    var selectedStore by remember { mutableStateOf<Store?>(null) }
    var selectedRoom by remember { mutableStateOf<Room?>(null) }
    var isLoadingStores by remember { mutableStateOf(false) }
    var isLoadingRooms by remember { mutableStateOf(false) }
    
    // 门店房间数据管理器
    val storeRoomDataManager = remember { StoreRoomDataManager(context) }
    
    // 状态管理
    var selectedRoomId by remember { mutableStateOf<String?>(null) }
    var selectedTimeWindow by remember { mutableStateOf(appConfig.defaultTimeWindow) }
    var brainWaveData by remember { mutableStateOf(listOf<BrainWaveDataPoint>()) }
    var swimLaneData by remember { mutableStateOf(listOf<BrainWaveDataPoint>()) }
    
    // 数据源管理器（用于蓝牙设备连接和数据采集）
    // 注意：现在使用NeuroSkyBluetoothManager替代DataSourceManager
    // val dataSourceManager = remember { DataSourceManager(context) }
    var dataSourceState by remember { mutableStateOf(DataSourceState.IDLE) }
    
    // 分析数据管理器
    val analysisDataManager = remember { AnalysisDataManager(context) }
    var analysisState by remember { mutableStateOf(AnalysisDataManagerState.IDLE) }
    var analysisResults by remember { mutableStateOf(listOf<TabletBrainWaveResponse>()) }
    
    // 原始设备数据日志
    var rawDeviceDataLog by remember { mutableStateOf(listOf<String>()) }
    var lastRawDataTimestamp by remember { mutableStateOf(0L) }
    var rawDataPacketCount by remember { mutableStateOf(0) }
    
    // 蓝牙连接状态管理（保持兼容性）
    var isBluetoothConnected by remember { mutableStateOf(false) }
    var isDataCollectionActive by remember { mutableStateOf(false) }
    
    // 会话管理状态
    var sessionState by remember { mutableStateOf(SessionState.IDLE) }
    var currentSession by remember { mutableStateOf<SessionResponse?>(null) }
    
    // 蓝牙设备选择弹窗状态
    var showDeviceSelectionDialog by remember { mutableStateOf(false) }
    var selectedBluetoothDevice by remember { mutableStateOf<BluetoothDevice?>(null) }
    
    // 初始化时加载门店列表
    LaunchedEffect(Unit) {
        isLoadingStores = true
        try {
            val storeList = storeRoomDataManager.getStores()
            println("收到门店列表，数量: ${storeList.size}")
            storeList.forEach { store ->
                println("门店 - ID: ${store.id}, 名称: ${store.name}")
            }
            stores = storeList
            println("门店状态更新完成，stores.size = ${stores.size}")
        } catch (e: Exception) {
            Log.e("MainActivity", "加载门店列表失败: ${e.message}")
            stores = emptyList() // 加载失败时清空门店列表
        } finally {
            isLoadingStores = false // 确保加载状态被重置
        }
    }
    
    // 协程作用域
    val scope = rememberCoroutineScope()
    
    // 选择门店时的处理
    fun onStoreSelected(store: Store) {
        selectedStore = store
        selectedRoom = null // 清空之前选择的房间
        println("选择了门店 - ID: ${store.id}, 名称: ${store.name}")
        
        // 获取该门店的房间列表
        println("开始获取门店ID=${store.id}的房间列表")
        isLoadingRooms = true // 开始加载房间
        scope.launch {
            try {
                val roomList = storeRoomDataManager.getRoomsByStoreId(store.id)
                println("获取到房间数量: ${roomList.size}")
                roomList.forEach { room ->
                    println("房间 - ID: ${room.id}, 名称: ${room.name}, 门店ID: ${room.store_id}")
                }
                rooms = roomList
                println("房间列表加载完成")
            } catch (e: Exception) {
                Log.e("MainActivity", "加载房间列表失败: ${e.message}")
                rooms = emptyList() // 加载失败时清空房间列表
            } finally {
                isLoadingRooms = false // 结束加载状态
            }
        }
    }
    
    // 清空房间列表
    fun clearRooms() {
        println("清空房间列表")
        rooms = emptyList()
    }
    
    // 当选择房间时，更新selectedRoomId
    LaunchedEffect(selectedRoom) {
        selectedRoomId = selectedRoom?.id?.toString()
    }

    
    // 滑动控制器
    val swimLaneController = remember { SlidingChartController() }
    val lineChartController = remember { SlidingChartController() }
    
    // NeuroSky服务实例
    val neuroSkyService = remember { NeuroSkyService(context) }
    
    // 配置NeuroSky服务
    LaunchedEffect(selectedRoomId) {
        if (selectedRoomId != null) {
            // 使用配置管理器的参数
            neuroSkyService.configure(
                roomId = selectedRoomId!!,
                apiBaseUrl = appConfig.apiBaseUrl,
                apiEndpoint = appConfig.apiEndpoint,
                sessionApiBaseUrl = appConfig.sessionApiBaseUrl
            )
            

            
            // 设置连接状态回调
            neuroSkyService.setOnConnectionStateChanged { connected ->
                println("🔗 NeuroSky连接状态变化: $connected")
                isBluetoothConnected = connected
                if (connected) {
                    // 蓝牙连接成功，但不直接设置会话状态为ACTIVE
                    // 会话状态应该由SessionManager管理，等待数据接收后创建会话
                    isDataCollectionActive = true
                    println("🔗 蓝牙连接成功，等待数据接收以创建会话")
                } else {
                    sessionState = SessionState.DISCONNECTED
                    isDataCollectionActive = false
                }
            }
            
            // 设置数据接收回调，用于更新UI状态
            neuroSkyService.setOnServerDataUpdated { dataPoints ->
                // 不在这里频繁更新sessionState，避免UI闪烁
                // sessionState由会话状态变化回调统一管理
                isDataCollectionActive = true
                
                // 处理接收到的服务端数据点，更新UI显示
                if (dataPoints.isNotEmpty()) {
                    val latestData = dataPoints.last()
                    val currentTime = System.currentTimeMillis()
                    rawDataPacketCount++
                    lastRawDataTimestamp = currentTime
                    
                    // 添加到日志
                    val logEntry = "${java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date(currentTime))} - " +
                            "睡眠阶段: ${latestData.sleepStage ?: "未知"}, 置信度: ${latestData.confidence ?: 0.0}, " +
                            "数据点数: ${latestData.receivedDataPoints}, 会话ID: ${latestData.sessionId}"
                    
                    rawDeviceDataLog = (rawDeviceDataLog + logEntry).takeLast(20)
                    
                    println("🔍 MainActivity 收到服务端数据: sleepStage=${latestData.sleepStage}, confidence=${latestData.confidence}, dataPoints=${latestData.receivedDataPoints}, sessionId=${latestData.sessionId}")
                    
                    // 🔧 修复：将服务端数据传递给AnalysisDataManager进行处理
                    // 这样AnalysisDataManager的setOnAnalysisResult回调就会被触发
                    if (latestData.success && latestData.sleepStage != null) {
                        println("📡 将服务端数据传递给AnalysisDataManager处理")
                        // 直接触发分析结果回调，因为服务端已经返回了分析结果
                        analysisDataManager.processServerResponse(latestData)
                    }
                }
            }
            
            // 注意：现在蓝牙连接由NeuroSkyBluetoothManager处理
            // 不再需要DataSourceManager的回调设置
        }
    }
    
    // 设置数据发送回调
    neuroSkyService.setOnDataSent { response ->
        // 数据发送成功的处理
    }
    
    // 设置错误回调
    neuroSkyService.setOnError { error ->
        // 错误处理
        isBluetoothConnected = false
        isDataCollectionActive = false
    }
    
    // 设置会话状态变化回调
     neuroSkyService.setOnSessionStateChanged { state, session ->
         println("收到会话状态变化 - 状态: $state, 会话ID: ${session?.id}")
         
         // 确保在主线程更新UI状态
         kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
             sessionState = state
             currentSession = session
             println("✅ UI状态已更新 - sessionState: $sessionState, currentSession: ${currentSession?.id}")
         }
         
         // 当会话创建成功时，更新AnalysisDataManager的会话ID并启动数据流程
         if (state == SessionState.ACTIVE && session != null) {
             println("🆔 更新AnalysisDataManager会话ID: ${session.id}")
             analysisDataManager.updateSessionId(session.id)
             println("🚀 启动数据流程")
             analysisDataManager.startDataFlow()
             println("✅ 数据流程已启动")
         }
     }
     
     // 设置会话错误回调
     neuroSkyService.setOnError { error ->
         println("❌ 会话错误: $error")
         
         // 区分不同类型的错误，避免因分析API错误导致会话状态错误重置
         if (error.contains("会话管理错误") || error.contains("会话创建失败") || error.contains("会话请求构建失败")) {
             // 只有真正的会话管理错误才重置会话状态
             kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
                 sessionState = SessionState.IDLE
                 isBluetoothConnected = false
                 isDataCollectionActive = false
             }
         } else if (error.contains("分析数据错误")) {
             // 分析数据错误不影响会话状态，只记录日志
             println("⚠️ 分析数据错误，保持当前连接状态: $error")
         } else {
             // 其他未知错误，为安全起见记录但不重置状态
             println("⚠️ 未知错误类型，保持当前连接状态: $error")
         }
     }
     
     // 获取当前用户状态（从最新数据点）
     val currentUserState = remember(brainWaveData) {
         brainWaveData.lastOrNull()?.userState ?: UserState.AWAKE
     }
     
     // 监听时间窗口变化，更新滑动控制器
     LaunchedEffect(selectedTimeWindow) {
         swimLaneController.setTimeWindow(selectedTimeWindow)
         lineChartController.setTimeWindow(selectedTimeWindow)
     }
     
     // 初始化分析数据管理器（仅在选择房间时初始化，不自动连接）
     LaunchedEffect(selectedRoomId) {
         if (selectedRoomId != null) {
             // 初始化分析数据管理器
              analysisDataManager.initialize(
                  baseUrl = appConfig.apiBaseUrl, // 从配置文件读取分析服务端URL
                  roomId = selectedRoomId!!,
                  userId = "user_${System.currentTimeMillis()}"
              )
             
             // 设置回调
             analysisDataManager.setOnStateChanged { state ->
                 analysisState = state
             }
             
             analysisDataManager.setOnAnalysisResult { result ->
                 // 将分析结果添加到列表中
                 analysisResults = (analysisResults + result).takeLast(100)
                 
                 // 添加调试日志
                 println("🔍 收到分析结果: success=${result.success}, sleepStage=${result.sleepStage}, confidence=${result.confidence}")
                 println("🔍 frequencyBands: ${result.frequencyBands}")
                 
                 // 根据分析结果创建可视化数据点
                if (result.success && result.frequencyBands != null) {
                    val bands = result.frequencyBands
                    
                    // 直接使用5个频段的数据
                    val total = bands.delta + bands.theta + bands.alpha + bands.beta + bands.gamma
                    
                    if (total > 0) {
                        val analysisDataPoint = BrainWaveDataPoint(
                            timestamp = System.currentTimeMillis(),
                            deltaRatio = (bands.delta / total).toFloat(),
                            thetaRatio = (bands.theta / total).toFloat(),
                            alphaRatio = (bands.alpha / total).toFloat(),
                            betaRatio = (bands.beta / total).toFloat(),
                            gammaRatio = (bands.gamma / total).toFloat(),
                             userState = UserState.fromServerResponse(result.sleepStage ?: "awake")
                        )
                         
                         // 添加到数据列表
                         brainWaveData = (brainWaveData + analysisDataPoint).takeLast(1000)
                         swimLaneData = (swimLaneData + analysisDataPoint).takeLast(1000)
                         
                         // 添加状态更新调试日志
                         println("📊 数据列表已更新: brainWaveData.size=${brainWaveData.size}, swimLaneData.size=${swimLaneData.size}")
                         
                         // 验证数据有效性
                         if (analysisDataPoint.isValid()) {
                             println("✅ 数据点有效，比例总和: ${analysisDataPoint.deltaRatio + analysisDataPoint.thetaRatio + analysisDataPoint.alphaRatio + analysisDataPoint.betaRatio + analysisDataPoint.gammaRatio}")
                         } else {
                             Log.w("MainActivity", "⚠️ 数据点无效，比例总和异常")
                         }
                     }
                 } else {
                     println("⚠️ 分析结果无效或frequencyBands为null: success=${result.success}, frequencyBands=${result.frequencyBands}")
                 }
             }
             
             analysisDataManager.setOnError { error ->
                 Log.e("MainActivity", "❌ 分析数据管理器错误: $error")
             }
         }
     }
     
     Column(
         modifier = Modifier
             .fillMaxSize()
             .background(
                 brush = Brush.verticalGradient(
                     colors = listOf(
                         TechGradientStart,
                         TechBackground,
                         TechGradientEnd
                     )
                 )
             )
             .windowInsetsPadding(WindowInsets.systemBars)
             .padding(16.dp),
         verticalArrangement = Arrangement.spacedBy(16.dp)
     ) {
         // 应用标题 - 添加科技感效果
         Box(
             modifier = Modifier.fillMaxWidth()
         ) {
             Text(
                 text = "睡眠监测系统",
                 style = MaterialTheme.typography.headlineLarge.copy(
                     shadow = Shadow(
                         color = TechGlow,
                         offset = Offset(0f, 0f),
                         blurRadius = 10f
                     )
                 ),
                 color = TechTextPrimary,
                 fontWeight = FontWeight.Bold,
                 modifier = Modifier.align(Alignment.Center)
             )
             
             // 添加装饰性边框
             Canvas(
                 modifier = Modifier
                     .fillMaxWidth()
                     .height(2.dp)
                     .align(Alignment.BottomCenter)
             ) {
                 drawLine(
                     brush = Brush.horizontalGradient(
                         colors = listOf(
                             Color.Transparent,
                             TechBlue,
                             TechCyan,
                             TechBlue,
                             Color.Transparent
                         )
                     ),
                     start = Offset(0f, size.height / 2),
                     end = Offset(size.width, size.height / 2),
                     strokeWidth = 4.dp.toPx()
                 )
             }
         }
         
         // 主要内容区域：针对平板优化的布局
         BoxWithConstraints(
             modifier = Modifier
                 .fillMaxWidth()
                 .weight(1f)
         ) {
             val screenWidth = maxWidth
             val screenHeight = maxHeight
             
             // 平板优化：确保图表有足够的显示空间
             val isTablet = screenWidth > 800.dp
             
             Row(
                 modifier = Modifier.fillMaxSize(),
                 horizontalArrangement = Arrangement.spacedBy(16.dp)
             ) {
                 // 左侧控制面板
                 Column(
                     modifier = Modifier
                         .weight(if (isTablet) 0.25f else 0.35f)
                         .fillMaxHeight()
                         .verticalScroll(rememberScrollState())
                         .padding(horizontal = if (isTablet) 6.dp else 8.dp), // 进一步减少水平内边距
                     verticalArrangement = Arrangement.spacedBy(if (isTablet) 4.dp else 6.dp) // 进一步减少间距
                 ) {
                     StoreRoomSelector(
                         stores = stores,
                         rooms = rooms,
                         selectedStore = selectedStore,
                         selectedRoom = selectedRoom,
                         onStoreSelected = { store -> onStoreSelected(store) },
                         onRoomSelected = { selectedRoom = it },
                         isLoading = isLoadingStores || isLoadingRooms,
                         modifier = Modifier.padding(vertical = if (isTablet) 4.dp else 6.dp) // 减少垂直内边距
                     )
                     
                     ControlPanel(
                         selectedTimeWindow = selectedTimeWindow,
                         onTimeWindowChanged = { selectedTimeWindow = it },
                         onClearData = { 
                             brainWaveData = emptyList()
                             swimLaneData = emptyList()
                         },
                         // 新增会话管理参数
                         sessionState = sessionState,
                         onConnectDevice = {
                             // 显示蓝牙设备选择弹窗
                             showDeviceSelectionDialog = true
                         },
                         onDisconnectDevice = {
                              try {
                                  println("🔌 开始断开蓝牙设备连接")
                                  // 使用协程启动断开过程
                                  kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO).launch {
                                      try {
                                          // 先停止NeuroSkyService服务
                                          neuroSkyService.stopService()
                                          println("✅ NeuroSkyService 服务已停止")
                                          
                                          // 断开会话连接
                                          neuroSkyService.disconnectSession()
                                          println("✅ 会话已断开")
                                          
                                          // 在主线程更新UI状态
                                          kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
                                              // 更新连接状态
                                              sessionState = SessionState.DISCONNECTED
                                              isBluetoothConnected = false
                                              isDataCollectionActive = false
                                              
                                              println("✅ 蓝牙设备已断开连接，会话已断开")
                                              println("ℹ️ 数据流程保持运行状态，等待重新连接")
                                          }
                                      } catch (e: Exception) {
                                          Log.e("MainActivity", "❌ 断开连接过程中发生异常: ${e.message}")
                                          e.printStackTrace()
                                          
                                          // 在主线程更新状态，确保UI一致性
                                          kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
                                              sessionState = SessionState.DISCONNECTED
                                              isBluetoothConnected = false
                                              isDataCollectionActive = false
                                          }
                                      }
                                  }
                              } catch (e: Exception) {
                                  Log.e("MainActivity", "❌ 启动断开连接过程时发生异常: ${e.message}")
                                  e.printStackTrace()
                                  // 防止应用崩溃，记录错误但不抛出异常
                                  // 确保即使出现异常也要更新状态
                                  sessionState = SessionState.DISCONNECTED
                                  isBluetoothConnected = false
                                  isDataCollectionActive = false
                              }
                          },
                         // 新增分析状态参数
                         analysisState = analysisState,
                         analysisSessionId = analysisDataManager.getSessionId()
                     )
                     
                     DeviceConnectionStatus(
                         roomId = selectedRoomId,
                         currentUserState = currentUserState,
                         isConnected = isDataCollectionActive
                     )
                     
                     DurationStatistics(
                         isConnected = isDataCollectionActive,
                         currentUserState = currentUserState,
                         modifier = Modifier.fillMaxWidth()
                     )
                     
                     // 平板模式下显示压缩版数据统计，手机模式下显示完整版
                     if (isTablet) {
                         // 压缩版数据统计卡片
                         Card(
                             modifier = Modifier.fillMaxWidth(),
                             colors = CardDefaults.cardColors(
                                 containerColor = Color(0xFF2A2A2A)
                             ),
                             shape = RoundedCornerShape(8.dp) // 减少圆角
                         ) {
                             Column(
                                 modifier = Modifier.padding(6.dp), // 进一步减少内边距
                                 verticalArrangement = Arrangement.spacedBy(3.dp) // 进一步减少间距
                             ) {
                                 Text(
                                     text = "数据统计",
                                     style = MaterialTheme.typography.titleSmall,
                                     color = Color.White,
                                     fontWeight = FontWeight.Bold
                                 )
                                 
                                 Row(
                                     modifier = Modifier.fillMaxWidth(),
                                     horizontalArrangement = Arrangement.SpaceBetween
                                 ) {
                                     Text(
                                         text = "总数据点: ${brainWaveData.size}",
                                         style = MaterialTheme.typography.bodySmall,
                                         color = Color(0xFFBBBBBB),
                                         fontSize = 11.sp
                                     )
                                     Text(
                                         text = "泳道数据: ${swimLaneData.size}",
                                         style = MaterialTheme.typography.bodySmall,
                                         color = Color(0xFFBBBBBB),
                                         fontSize = 11.sp
                                     )
                                 }
                             }
                         }
                     } else {
                         DataStatisticsCard(
                             brainWaveData = brainWaveData,
                             swimLaneData = swimLaneData
                         )
                         
                         // 测试用：显示处理后的脑波数据
                         Card(
                             modifier = Modifier.fillMaxWidth(),
                             colors = CardDefaults.cardColors(
                                 containerColor = Color(0xFF2A2A2A)
                             )
                         ) {
                             Column(
                                 modifier = Modifier.padding(12.dp),
                                 verticalArrangement = Arrangement.spacedBy(8.dp)
                             ) {
                                 Text(
                                     text = "原始设备数据 (测试)",
                                     style = MaterialTheme.typography.titleMedium,
                                     color = Color.White,
                                     fontWeight = FontWeight.Bold
                                 )
                                 
                                 Row(
                                     modifier = Modifier.fillMaxWidth(),
                                     horizontalArrangement = Arrangement.SpaceBetween
                                 ) {
                                     Text(
                                         text = "数据包: $rawDataPacketCount",
                                         style = MaterialTheme.typography.bodySmall,
                                         color = Color(0xFFBBBBBB)
                                     )
                                     if (lastRawDataTimestamp > 0) {
                                         Text(
                                             text = "最后更新: ${java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date(lastRawDataTimestamp))}",
                                             style = MaterialTheme.typography.bodySmall,
                                             color = Color(0xFFBBBBBB)
                                         )
                                     }
                                 }
                                 
                                 if (rawDeviceDataLog.isNotEmpty()) {
                                     Column(
                                         modifier = Modifier
                                             .fillMaxWidth()
                                             .heightIn(max = 120.dp)
                                             .verticalScroll(rememberScrollState()),
                                         verticalArrangement = Arrangement.spacedBy(2.dp)
                                     ) {
                                         rawDeviceDataLog.takeLast(5).forEach { logEntry ->
                                             Text(
                                                 text = logEntry,
                                                 style = MaterialTheme.typography.bodySmall,
                                                 color = Color(0xFF90CAF9),
                                                 fontSize = 10.sp
                                             )
                                         }
                                     }
                                 } else {
                                     Text(
                                         text = "等待设备数据...",
                                         style = MaterialTheme.typography.bodySmall,
                                         color = Color(0xFF666666),
                                         fontStyle = androidx.compose.ui.text.font.FontStyle.Italic
                                     )
                                 }
                             }
                         }
                         
                         InfoCard()
                     }
                 }
                 
                 // 右侧：图表区域（平板上优先保证图表完整显示）
                 Column(
                     modifier = Modifier
                         .weight(if (isTablet) 0.75f else 0.65f)
                         .fillMaxHeight(),
                     verticalArrangement = Arrangement.spacedBy(16.dp)
                 ) {
                     // 泳道图（右上角）- 平板上确保最小高度
                     Card(
                         modifier = Modifier
                             .fillMaxWidth()
                             .weight(1f)
                             .heightIn(min = if (isTablet) 300.dp else 200.dp),
                         colors = CardDefaults.cardColors(
                             containerColor = Color(0xFF2A2A2A)
                         )
                     ) {
                         SwimLaneChart(
                             dataPoints = swimLaneData,
                             config = SwimLaneChartConfig(
                                 displayTimeWindowSeconds = selectedTimeWindow
                             ),
                             modifier = Modifier.fillMaxSize(),
                             slidingController = if (selectedTimeWindow == -1) null else swimLaneController
                         )
                     }
                     
                     // 用户状态折线图（右下角）- 平板上确保最小高度
                     Card(
                         modifier = Modifier
                             .fillMaxWidth()
                             .weight(1f)
                             .heightIn(min = if (isTablet) 300.dp else 200.dp),
                         colors = CardDefaults.cardColors(
                             containerColor = Color(0xFF2A2A2A)
                         )
                     ) {
                         LineChart(
                             dataPoints = brainWaveData,
                             config = LineChartConfig(
                                 displayTimeWindowSeconds = selectedTimeWindow,
                                 showLabels = true  // 明确设置为true
                             ),
                             modifier = Modifier.fillMaxSize(),
                             slidingController = if (selectedTimeWindow == -1) null else lineChartController
                         )
                     }
                 }
             }
         }
         
         // 蓝牙设备选择弹窗
         if (showDeviceSelectionDialog) {
             BluetoothDeviceSelectionDialog(
                 isVisible = showDeviceSelectionDialog,
                 onDeviceSelected = { device ->
                     selectedBluetoothDevice = device
                     showDeviceSelectionDialog = false
                     
                     // 设置连接状态为连接中
                     sessionState = SessionState.CONNECTING
                     
                     // 连接到选中的设备并启动完整的数据流程
                     if (selectedRoomId != null) {
                         kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
                             try {
                                 // 准备待创建的会话信息
                                 neuroSkyService.preparePendingSession(selectedRoomId.toString())
                                 println("MainActivity: 已设置待创建会话 - roomId: $selectedRoomId")
                                 
                                 // 连接蓝牙设备
                                 println("🔗 正在连接到蓝牙设备...")
                                 val connected = neuroSkyService.startService(device.address)
                                 if (connected) {
                                     println("MainActivity: 蓝牙连接成功，等待数据接收...")
                                 } else {
                                     println("MainActivity: 蓝牙连接失败")
                                     sessionState = SessionState.DISCONNECTED
                                 }
                             } catch (e: Exception) {
                                 println("❌ 设备连接流程执行异常: ${e.message}")
                                 e.printStackTrace()
                                 sessionState = SessionState.DISCONNECTED
                             }
                         }
                     } else {
                         println("❌ 连接失败：未选择房间")
                         sessionState = SessionState.IDLE
                     }
                 },
                 onDismiss = {
                     showDeviceSelectionDialog = false
                 }
             )
         }
     }
 }

@Composable
fun ControlPanel(
    selectedTimeWindow: Int,
    onTimeWindowChanged: (Int) -> Unit,
    onClearData: () -> Unit,
    // 新增会话管理参数
    sessionState: SessionState,
    onConnectDevice: () -> Unit,
    onDisconnectDevice: () -> Unit,
    // 新增分析状态参数
    analysisState: AnalysisDataManagerState,
    analysisSessionId: String
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .shadow(
                elevation = 8.dp,
                shape = RoundedCornerShape(12.dp),
                ambientColor = TechGlow,
                spotColor = TechBlue
            ),
        colors = CardDefaults.cardColors(
            containerColor = TechSurface
        ),
        shape = RoundedCornerShape(12.dp),
        border = BorderStroke(1.dp, TechBorder)
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            // 标题带发光效果
            Text(
                text = "控制面板",
                style = MaterialTheme.typography.titleMedium.copy(
                    shadow = Shadow(
                        color = TechBlue,
                        offset = Offset(0f, 0f),
                        blurRadius = 8f
                    )
                ),
                color = TechTextPrimary,
                fontWeight = FontWeight.Bold
            )
            
            // 时间窗口选择
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "显示时间:",
                    color = TechTextSecondary,
                    style = MaterialTheme.typography.bodyMedium
                )
                
                TimeWindowDropdown(
                    currentSelection = selectedTimeWindow,
                    onSelectionChange = onTimeWindowChanged,
                    modifier = Modifier.weight(1f)
                )
            }
            
            // 按钮组 - 科技感样式
            Row(
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                // 连接设备按钮 - 蓝牙设备连接功能
                Button(
                    onClick = {
                        println("🔘 按钮点击 - 当前sessionState: $sessionState")
                        when (sessionState) {
                            SessionState.IDLE, SessionState.DISCONNECTED -> {
                                println("🔗 执行连接设备操作")
                                onConnectDevice()
                            }
                            SessionState.ACTIVE -> {
                                println("🔌 执行断开设备操作")
                                onDisconnectDevice()
                            }
                            else -> {
                                println("⏳ 连接中状态，忽略点击")
                            } // CONNECTING状态时不响应点击
                        }
                    },
                    enabled = sessionState != SessionState.CONNECTING,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = when (sessionState) {
                            SessionState.ACTIVE -> {
                                println("🎨 按钮颜色设置为错误色 (ACTIVE状态)")
                                TechError
                            }
                            else -> {
                                println("🎨 按钮颜色设置为蓝色 (非ACTIVE状态)")
                                TechBlue
                            }
                        },
                        contentColor = TechBackground,
                        disabledContainerColor = TechBorder,
                        disabledContentColor = TechTextSecondary
                    ),
                    modifier = Modifier
                        .weight(1f)
                        .shadow(
                            elevation = 4.dp,
                            shape = RoundedCornerShape(8.dp),
                            ambientColor = when (sessionState) {
                                SessionState.ACTIVE -> TechError
                                else -> TechBlue
                            }
                        ),
                    shape = RoundedCornerShape(8.dp)
                ) {
                    val buttonText = when (sessionState) {
                        SessionState.IDLE, SessionState.DISCONNECTED -> "连接设备"
                        SessionState.CONNECTING -> "连接中..."
                        SessionState.ACTIVE -> "断开设备"
                    }
                    println("📝 按钮文本: $buttonText (sessionState: $sessionState)")
                    
                    Text(
                        text = buttonText,
                        style = MaterialTheme.typography.bodyMedium,
                        fontWeight = FontWeight.SemiBold
                    )
                }
                
                OutlinedButton(
                    onClick = onClearData,
                    colors = ButtonDefaults.outlinedButtonColors(
                        contentColor = TechTextPrimary,
                        containerColor = Color.Transparent
                    ),
                    border = BorderStroke(1.dp, TechBorder),
                    modifier = Modifier.weight(1f),
                    shape = RoundedCornerShape(8.dp)
                ) {
                    Text(
                        text = "清空数据",
                        style = MaterialTheme.typography.bodyMedium,
                        fontWeight = FontWeight.SemiBold
                    )
                }
            }
        }
    }
}

@Composable
fun DataStatisticsCard(
    brainWaveData: List<BrainWaveDataPoint>,
    swimLaneData: List<BrainWaveDataPoint>
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFF2A2A2A)
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            Text(
                text = "数据统计",
                style = MaterialTheme.typography.titleMedium,
                color = Color.White,
                fontWeight = FontWeight.Bold
            )
            
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                StatItem("脑波数据", "${brainWaveData.size}")
                StatItem("泳道数据", "${swimLaneData.size}")
            }
            
            if (brainWaveData.isNotEmpty()) {
                Text(
                    text = "数据概览:",
                    color = Color.White,
                    style = MaterialTheme.typography.bodyMedium
                )
                
                val latestData = brainWaveData.lastOrNull()
                if (latestData != null) {
                    Text(
                        text = "最新状态: ${latestData.userState}",
                        color = Color(0xFFBBBBBB),
                        style = MaterialTheme.typography.bodySmall
                    )
                }
            }
        }
    }
}

@Composable
fun StatItem(label: String, value: String) {
    Column {
        Text(
            text = label,
            color = Color.Gray,
            style = MaterialTheme.typography.bodySmall
        )
        Text(
            text = value,
            color = Color.White,
            style = MaterialTheme.typography.bodyMedium,
            fontWeight = FontWeight.Bold
        )
    }
}

@Composable
fun InfoCard() {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFF2A2A2A)
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            Text(
                text = "使用说明",
                style = MaterialTheme.typography.titleMedium,
                color = Color.White,
                fontWeight = FontWeight.Bold
            )
            
            Text(
                text = "• 点击\"连接设备\"按钮开始连接蓝牙设备并采集脑波数据\n" +
                        "• 泳道图显示五个频域的实时变化\n" +
                        "• 不同颜色代表不同的脑波频域\n" +
                        "• 横轴表示时间，纵轴表示各频域比例",
                color = Color.Gray,
                style = MaterialTheme.typography.bodySmall
            )
        }
    }
}

@Preview(showBackground = true)
@Composable
fun BrainWaveAppPreview() {
    Brain_waveTheme {
        Surface(
            modifier = Modifier.fillMaxSize(),
            color = Color(0xFF1A1A1A)
        ) {
            BrainWaveApp()
        }
    }
}